package com.ifast.album.controller;

import java.util.Arrays;
import java.util.Optional;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.ifast.album.domain.AlbumConf;
import com.ifast.album.domain.AlbumInfo;
import com.ifast.album.service.AlbumConfService;
import com.ifast.album.service.AlbumInfoService;
import com.ifast.common.annotation.Log;
import com.ifast.common.annotation.OperateRecord;
import com.ifast.common.base.AdminBaseController;
import com.ifast.common.utils.Const;
import com.ifast.sys.domain.UserDO;
import com.ifast.sys.filter.SameUrlData;
import com.luculent.util.extension.api.Result;
import com.xiaoleilu.hutool.util.StrUtil;

/**
 * 相册管理
 * @author shíQíang㊚
 * @date 2019年4月9日10:05:14
 */
@RequestMapping("/album/info")
@Controller
public class AlbumInfoController extends AdminBaseController {
	
    private String preHtml = "lucky/album/info/";
    @Autowired
    private AlbumInfoService albumInfoService;
    @Autowired
    private AlbumConfService albumConfService;
    
    @GetMapping("/qyList") 
    @RequiresPermissions("album:info:qyList")
    String qyList(Model model) {
        return preHtml + "qy_list";
    }
     
    @GetMapping("/qyLoop") 
    @RequiresPermissions("album:info:qyList")
    String qyLoop(Model model) {
    	AlbumInfo album = albumInfoService.selectOne(new EntityWrapper<AlbumInfo>().eq("DW_CODE", this.getUser().getDwCode()).eq("CLASSIFY",Const.album.album_loop.getId()).andNew().eq("DO_TYPE", Const.albumDoType.type_loop.getValue()).or().isNull("DO_TYPE"));
		if(album == null){
			album = albumInfoService.createAlbum(Const.album.album_loop, this.getUser().getId()+"",this.getUser().getDeptId(), this.getUser().getDwCode(),"轮播图相册", 0,Const.albumDoType.type_loop.getValue()); 
		}
		AlbumConf conf = albumConfService.selectOne(new EntityWrapper<AlbumConf>().eq("DW_CODE", this.getUser().getDwCode()));
        if(conf == null){
        	conf = AlbumConf.builder().loops(Const.loops).userId(this.getUserId().toString()).dwCode(this.getUser().getDwCode()).type("0").deptId(this.getUser().getDeptId()).build();
        	albumConfService.insert(conf);
        }
        model.addAttribute("conf", conf);
        model.addAttribute("qiYongType", conf.getType());
		model.addAttribute("albumId", album.getId());
        return preHtml + "qy_loop";
    }
    
    @GetMapping("qyListData") 
    @OperateRecord(OperateName = "列表",ModellName ="相册模块")
    @ResponseBody 
    public Result<Page<AlbumInfo>> qyListData(Model model,AlbumInfo explain) {
    	 Page<AlbumInfo> page = this.albumInfoService.selectPage(getPage(AlbumInfo.class),new EntityWrapper<AlbumInfo>()
        		.eq("DW_CODE", this.getUser().getDwCode())
        		.eq("DELFLAG", 0) 
        		.like(StringUtils.isNotBlank(explain.getAlbumName()),"ALBUM_NAME",explain.getAlbumName())
        		.eq(StrUtil.isNotBlank(explain.getClassify()),"classify",explain.getClassify())
        		.andNew().eq("DO_TYPE", Const.albumDoType.type_nomal.getValue()).or().isNull("DO_TYPE")
        		.orderBy("sort").orderBy("create_time",false));
        Optional.ofNullable(page.getRecords()).ifPresent(infos -> infos.parallelStream().forEach(info -> {
        	if(StringUtils.isBlank(info.getCoverUrl()))
        		info.setCoverUrl("/img/album.png");
        }));
        
        return Result.ok(page);
    }
    
    @GetMapping("qyListLoop") 
    @OperateRecord(OperateName = "列表",ModellName ="相册模块")
    @ResponseBody 
    public Result<Page<AlbumInfo>> qyListLoop(Model model) {
    	 Page<AlbumInfo> page = this.albumInfoService.selectPage(getPage(AlbumInfo.class),new EntityWrapper<AlbumInfo>()
        		.eq("DW_CODE", this.getUser().getDwCode())
        		.eq("DEPT_ID", this.getUser().getDeptId())
        		.eq("DO_TYPE", Const.albumDoType.type_loop.getValue())
        		.eq("DELFLAG", 0)
        		.eq("classify",Const.album.album_loop.getId())
        		.orderBy("sort").orderBy("create_time",false));
        Optional.ofNullable(page.getRecords()).ifPresent(infos -> infos.parallelStream().forEach(info -> {
        	if(StringUtils.isBlank(info.getCoverUrl()))
        		info.setCoverUrl("/img/album.png"); 
        }));
        
        return Result.ok(page);
    }
    
    /**
     *  
     * @param model
     * @param id 
     */
    @GetMapping("/add")
    @RequiresPermissions("album:info:add")
    public String add(Model model, String id){ 
        return  preHtml+"add";
    }
    /**
     * 编辑
     * @param model
     * @param id 
     */
    @GetMapping("/edit/{id}")
    @RequiresPermissions("album:info:edit")
    public String edit(Model model,@PathVariable("id") String id){
    	model.addAttribute("info",albumInfoService.selectById(id));
        return  preHtml+"edit";
    } 
    
    /**
     * 编辑
     * @param model
     * @param id 
     */
    @GetMapping("/loopEdit/{id}") 
    public String loopEdit(Model model,@PathVariable("id") String id){
    	model.addAttribute("conf",albumConfService.selectById(id));
        return  preHtml+"loop_edit";
    } 
    /**
     * 查看
     * @param model
     * @param id 
     */
    @GetMapping("/view/{id}")
    @RequiresPermissions("album:info:edit")
    public String view(Model model,@PathVariable("id") String id){
    	model.addAttribute("info",albumInfoService.selectById(id));
        return  preHtml+"view";
    }
    /**
     * 删除
     * @param model
     * @param id 
     */
    @PostMapping("/remove")
    @ResponseBody
    @Log("删除")
    @RequiresPermissions("album:info:remove")
    public Result<?> remove(Model model,String id){ 
        return  albumInfoService.delete(id);
    } 
    
    /**
     * 删除
     * @param model
     * @param id 
     */
    @PostMapping("/qiYong")
    @ResponseBody 
    public Result<?> qiYong(Model model,String id,String type){
    	AlbumConf conf = albumConfService.selectOne(new EntityWrapper<AlbumConf>().eq("DW_CODE", this.getUser().getDwCode()));
        if(conf == null){
        	albumConfService.insert(AlbumConf.builder().loops(Const.loops).userId(this.getUserId().toString()).dwCode(this.getUser().getDwCode()).albumId(id).type(type).deptId(this.getUser().getDeptId()).build());
        }else{
        	albumConfService.updateById(conf.setType(type));
        }
    	return Result.ok();
    }
    /**
     * 批量删除
     */
    @PostMapping("/batchRemove")
    @ResponseBody
    @RequiresPermissions("album:info:batchRemove")
    @Log("批量删除")
    public Result<?> batchRemove(@RequestParam("ids[]") String[] ids) { 
        return albumInfoService.deleteBatch(Arrays.asList(ids));
    }

    /**
     * 保存 
     */
    @PostMapping("/save")
    @ResponseBody
    @SameUrlData
    @OperateRecord(OperateName = "保存相册",ModellName ="相册模块" )
    public Result<?> saveSubject(String albumId,String name,Integer sort) {
        try{ 
        	UserDO user = this.getUser();
        	return albumInfoService.save(Const.album.album_nomal,user.getId().toString(),user.getDeptId(),user.getDwCode(),albumId,name,sort);
        }catch (Exception e){
            log.error(e.toString(),e);
            return Result.fail();
        } 
    } 
    
    /**
     * 保存 
     */
    @PostMapping("/updateLoop")
    @ResponseBody
    @SameUrlData
    @OperateRecord(OperateName = "保存相册",ModellName ="相册模块" )
    public Result<?> updateLoop(String confId,Integer loops) {
        try{ 
        	AlbumConf conf = albumConfService.selectOne(new EntityWrapper<AlbumConf>().eq("ID", confId));
            if(conf != null){
            	albumConfService.updateById(conf.setLoops(loops));
            	return Result.ok();
            }else{
            	return Result.fail();
            }
        }catch (Exception e){
            log.error(e.toString(),e);
            return Result.fail();
        } 
    } 
}